package bg.tu.varna.pms.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DataBaseHandler {

	private String mUserName;
	private String mPassWord;
	private Object dbms;
	private String serverName;
	private int portNumber;
	private String dbName;
	private Connection mConnection;
	
	public DataBaseHandler(String User,String Pass, int Port, String DBName) throws SQLException
	{
		mUserName = User;
		mPassWord = Pass;
//		dbms = DBMS;
//		serverName = Server;
		portNumber = Port;
		dbName = DBName;
		makeConnection();
	}
	
	private void makeConnection() throws SQLException {
	    Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dbName,"root", "");	 
		} catch (SQLException e) {
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			return;
		} catch (ClassNotFoundException e) {
			System.out.println("Where is your MySQL JDBC Driver?");
			e.printStackTrace();
			return;
		}

//		    conn = DriverManager.getConnection("jdbc:mysql://localhost:"+portNumber+"/"+dbName,mUserName, mPassWord);
/*		    Properties connectionProps = new Properties();
		    connectionProps.put("user", this.mUserName);
		    connectionProps.put("password", this.mPassWord);
		    
		    conn = DriverManager.getConnection("jdbc:" + this.dbms + "://" + this.serverName + ":" + this.portNumber + "/",connectionProps);
		   // System.out.println("Connected to database");
		    */
		    mConnection = conn;
	}
	
	public Connection getConnection() 
	{
		return mConnection;
	}
	
	@SuppressWarnings("finally")
	public ResultSet SELECT(String selectStatement)
	{
		try
		{
			Statement stmt = mConnection.createStatement();
			ResultSet rs;
    
			rs = stmt.executeQuery(selectStatement);
			return rs;
		} 
		catch (Exception e)
		{
			System.err.println("Got an exception! ");
			System.err.println(e.getMessage());
		}
		finally 
		{
			return null;
		}
	}
	
	public boolean INSERT(String TableName,Object[] Columns) throws SQLException
	{
		Statement stmt = mConnection.createStatement();
		String values = "";
		for(int i = 0;i<Columns.length;i++)
		{
			values += "'"+Columns[i].toString()+"'";
			if((i+1) != Columns.length)
				values += ", ";
		}
		int rows = stmt.executeUpdate("INSERT INTO "+TableName+" VALUES ("+values+")");
		
		if(rows == 1)
			return true;
		else
			return false;
	}
	
	public void Close()
	{
			try 
			{
				mConnection.close();
			} 
			catch (SQLException e) 
			{
				e.printStackTrace();
			}
	}
	
	
	public static void main(String[] args) throws SQLException {
		// TODO Auto-generated method stub
		
		
	}

}
